//
//  HMRefreshControl.swift
//  Black22
//
//  Created by Apple on 16/11/24.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit

private enum HMRefreshType: Int {
    //  默认状态
    case normal = 0
    //  松手就刷新状态
    case pulling = 1
    //  正在刷新
    case refreshing = 2
}


private let HMRefreshControlH: CGFloat = 50
//  自定义下拉刷新控件
class HMRefreshControl: UIControl {
    
    //  当前刷新状态
    fileprivate var refreshType: HMRefreshType = .normal {
        didSet {
            switch refreshType {
            case .normal:
                print("下拉刷新")
                //  箭头显示，箭头重置，风火轮停止，内容改成下拉刷新
                iconImageView.isHidden = false
                indicatorView.stopAnimating()
                UIView.animate(withDuration: 0.25, animations: {
                    self.iconImageView.transform = CGAffineTransform.identity
                })
                //  如果上一次刷新状态是正在刷新，停留位置重置
                if oldValue == .refreshing {
                    //  设置停留
                    UIView.animate(withDuration: 0.25, animations: {
                        self.currentScrollView?.contentInset.top -= HMRefreshControlH
                    })
                }
                messageLabel.text = "下拉刷新"
                
                
            case .pulling:
                print("松手就刷新")
                //  箭头调转，内容改成松手就刷新
                UIView.animate(withDuration: 0.25, animations: { 
                    self.iconImageView.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI))
                })
                messageLabel.text = "松手就刷新"
                
                
            case .refreshing:
                print("正在刷新")
                //  隐藏箭头,开启风火轮,内容改成正在刷新
                iconImageView.isHidden = true
                indicatorView.startAnimating()
                messageLabel.text = "正在刷新..."
                
                //  设置停留
                UIView.animate(withDuration: 0.25, animations: { 
                    self.currentScrollView?.contentInset.top += HMRefreshControlH
                })
                
                
                //  手动发送事件
                sendActions(for: .valueChanged)
            }
        }
    }

    //  当前滚动的父视图
    fileprivate var currentScrollView: UIScrollView?
    
    // MARK:    --懒加载
    private lazy var iconImageView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    private lazy var messageLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.gray
        label.font = UIFont.systemFont(ofSize: 12)
        label.text = "下拉刷新"
        return label
    }()
    
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        addSubview(iconImageView)
        addSubview(messageLabel)
        addSubview(indicatorView)
        
        iconImageView.translatesAutoresizingMaskIntoConstraints = false
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        indicatorView.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute: NSLayoutAttribute.centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute: NSLayoutAttribute.centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .centerX, relatedBy: .equal, toItem: iconImageView, attribute: .centerX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .centerY, relatedBy: .equal, toItem: iconImageView, attribute: .centerY, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .leading, relatedBy: .equal, toItem: iconImageView, attribute: .trailing, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .centerY, relatedBy: .equal, toItem: iconImageView, attribute: .centerY, multiplier: 1, constant: 0))
        
        
        backgroundColor = UIColor.red
    }
    
    //  通过将要添加到那个父视图上会调用该方法，获取父视图
    override func willMove(toSuperview newSuperview: UIView?) {
        guard let scrollView = newSuperview as? UIScrollView else {
            return
        }
        //  代码执行到此，是我们关心可以滚动的父视图
        self.frame = CGRect(x: 0, y: -HMRefreshControlH, width: scrollView.frame.size.width, height: HMRefreshControlH)
        
        //  使用kvo监听其父视图的滚动
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
        currentScrollView = scrollView
    }
    
    //  kvo监听方法
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        let contentOffsetY = currentScrollView!.contentOffset.y
        //  计算临界点, 为了和垂直方向的偏移量好比较，保持类型相同
        let maxY = -(currentScrollView!.contentInset.top + HMRefreshControlH)
        
        //  判断是否在拖动
        if currentScrollView!.isDragging {
            
            //  拖动情况下只有两种状态，normal和pulling
            if contentOffsetY < maxY && refreshType == .normal {
                print("pulling")
                refreshType = .pulling
            } else if contentOffsetY >= maxY && refreshType == .pulling {
                print("normal")
                refreshType = .normal
            }
            
            
        } else {
        
            //  进入正在刷新状态 有两个条件，1.松手， 2.上一次的状态是pulling
            if refreshType == .pulling {
                print("refreshing")
                refreshType = .refreshing
            
            }
            
        }
        
        
    }
    
    //  结束刷新
    func endRefreshing () -> Void {
        //  状态设置为normal状态
        refreshType = .normal
    }
    
    
    //  移除kvo
    deinit {
        currentScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    
    

}
